import React, {PureComponent} from 'react';
// import { connect } from 'dva';
import style from "styled-components";
import {Form, Input, Button, Menu, Icon, Modal, message} from 'antd';
import {
  searchRoleAndRoleGroupList, enterpriseRoleGroupDelete, systemComRoleRroupBatchInsertRoleGroup
} from "../../../../services/api";
import {dataSource} from "../../../../components/HeaderSearch";
import bcx_utils from "../../../../common/bcx_utils";
// @connect(state => ({
//   monitor: state.monitor,
// }))

const FormItem = Form.Item;
// const { Search } = Input;
// const { Option } = Select;
const {SubMenu} = Menu;

/**
 * 配置角色组
 */
export default class InitialRoleGroup extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      dataSource: [],
    };

  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.searchRoleAndRoleGroupList();
  }
  componentWillReceiveProps = () => {

  }
  /******************************ajax请求******************************/

    //角色组及角色列表获取
  searchRoleAndRoleGroupList = () => {
    searchRoleAndRoleGroupList().then(
      ({data}) => {
        console.log(data);
        this.setState({dataSource: data});
      },
      (err) => {
        message.error("角色组初始化失败，请联系管理员");
        console.log(err);
      }
    );
  }


  /******************************相关事件******************************/


  handleSubmit = (e) => {
    e.preventDefault();
    //批量操作角色组
    bcx_utils.preventRepeatAsync((callback) => callback((resolve) => {
      const ajaxArr = this.state.dataSource.map(({roleGroupId, roleGroupName}) => ({
        roleGroupId, roleGroupName
      }));
      systemComRoleRroupBatchInsertRoleGroup({comRoleGroups: JSON.stringify(ajaxArr)}).then(
        (data) => {
          console.log(data);
          resolve();
        },
        (err) => {
          console.log(err);
          resolve();
        }
      );

    }))
  }

  inputChange = (index, e) => {
    const dataSource = bcx_utils.jsoncopy(this.state.dataSource);
    dataSource[index].roleGroupName = e.target.value;
    this.setState({dataSource});
  }

  inputRemove = ({roleGroupId}, index) => {
    const dataSource = bcx_utils.jsoncopy(this.state.dataSource);
    if (roleGroupId !== "") {
      Modal.confirm({
        title: '确认删除该记录?',
        content: '',
        onOk: () => {
          //角色组删除功能
          enterpriseRoleGroupDelete({roleGroupId}).then(
            ({msg}) => {
              message.success(msg);
              this.searchRoleAndRoleGroupList();
            },
            (err) => {
              message.error(err.msg);
            }
          );
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    } else {
      this.setState({dataSource: dataSource.filter((val, i) => i !== index)});
    }
  }

  addRoleGroup = () => {
    const dataSource = bcx_utils.jsoncopy(this.state.dataSource);
    dataSource.push({
      roleGroupId: "",
      roleGroupName: "",
    });
    this.setState({dataSource});
  }


  /******************************render******************************/
    //render每一条角色组记录
  renderItems = () => {
    const roleItems = this.state.dataSource.map((value, index) => {

      const ifModificate = index !== 0;//判断是否第一项默认组

      return (
        <div className="roleitem" key={index}>
          <div className="l ant-form-item-required">
            角色组{index + 1}:
          </div>
          <div className="c">
            <Input placeholder="请输入组名称"
                   style={{width: 400, marginRight: 8}}
                   maxLength='20'
                   value={value.roleGroupName}
                   disabled={!ifModificate}
                   onChange={this.inputChange.bind(this, index)}/>
          </div>
          <div className="r">
            {ifModificate && (
              <Icon
                className="dynamic-delete-button"
                type="minus-circle-o"
                onClick={this.inputRemove.bind(this, value, index)}
              />
            )}
          </div>
        </div>
      );
    });
    return roleItems;
  }

  render() {

    return (
      <Container>
        <div className="department-content">
          <div className="department-right">
            <span className="department-title" style={{display: "none"}}>{this.state.caption}</span>
            <div>
              {this.renderItems()}
              <div>
                <Button type="dashed" onClick={this.addRoleGroup} style={{width: '500px'}}>
                  <Icon type="plus"/> 添加
                </Button>
              </div>
              <div style={{marginTop: 32}}>
                {/*<Button onClick={() => {*/}
                  {/*this.props.setRoute('InitialDepartmentalInstitutions');*/}
                {/*}} style={{marginRight: "8px"}}>取消</Button>*/}
                <Button onClick={this.handleSubmit} className="submit" type="primary" htmlType="submit">保存</Button>
              </div>
            </div>
          </div>
        </div>
      </Container>
    );
  }
}

/*********************样式*************************** */
const
  Container = style.div`{
    .roleitem{
      display: inline-block;
      width: 700px;
      margin-bottom: 20px;
      border-bottom: 1px solid #f3f3f3;
      padding-bottom: 17px;
      text-align: left;
       >div{
        display: inline-block;
       }
      .l{
        text-align: right;
        width: 120px;
        margin-right: 10px;
      }
      .r{
       margin-left: 37px;
      }
      .c{
        
      }
    }
    .dynamic-delete-button {
        cursor: pointer;
        position: relative;
        top: 4px;
        font-size: 24px;
        color: #d9d9d9;
        transition: all .3s;
    }
    .dynamic-delete-button:hover {
        color: #777;
    }
    .dynamic-delete-button[disabled] {
        cursor: not-allowed;
        opacity: 0.5;
    }

    .ant-btn-primary{
        background-color: #0F71FF;
    }
    .ant-menu-submenu > .ant-menu{
        background:#fff;
    }

    .department-content{
        min-height: 600px;
        background: #fff;
        border-radius: 5px;
        position: relative;
        text-align: center;
        .department-right{
            display: inline-block;
            margin-left:1px;
            padding:0px 24px;
            min-height:600px;
            .department-title{
                font-size: 16px;
                color: #333333;
            }
        }
      }
}`;
